<template>
  <div class="searchBar-container" :style="{ width: searchBarWidth + 'px' }">
    <el-card class="searchBar-card" shadow="hover">
      <!-- 数据的提交都封装成表单的形式 -->
      <el-form ref="advancedForm" :model="advancedForm" label-width="100px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="标题 / 内容" prop="titleAndContent">
              <!-- 消除前后的空格 -->
              <el-input
                v-model.trim="advancedForm.keyword"
                placeholder="请输入需要检索的标题或内容"
                :size="formItemSize"
                type="text"
                clearable
                maxlength="200"
                show-word-limit
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="标签" prop="tags">
              <!-- 标签是从后端动态请求的,开启多选 -->
              <!-- 将选择的多个标签合并为一个 -->
              <el-select
                v-model="advancedForm.tagId"
                style="width: 100%"
                :size="formItemSize"
                multiple
                collapse-tags
                placeholder="请选择文章的标签"
              >
                <el-option
                  v-for="item in allTags"
                  :key="item.tagId"
                  :label="item.tagName"
                  :value="item.tagId"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="文章类型" prop="articleType">
              <!-- 选项的数目少，就不进行合并 -->
              <el-select
                v-model="advancedForm.kind"
                placeholder="请选择文章类型"
                style="width: 100%"
                :size="formItemSize"
                multiple
              >
                <el-option label="原创" :value="0"></el-option>
                <el-option label="转载" :value="1"></el-option>
                <el-option label="翻译" :value="2"></el-option>
              </el-select> </el-form-item
          ></el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="时间" prop="date">
              <!-- 设置unlink-panels取消联动 -->
              <!-- 同时设置快捷选择 -->
              <el-date-picker
                type="daterange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                style="width: 100%"
                :size="formItemSize"
                unlink-panels
                :picker-options="pickerOptions"
                v-model="advancedForm.createTime"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="作者" prop="author">
              <!-- 搜索作者检查的是所有作者中包含该词或字的人 -->
              <el-input
                v-model="advancedForm.authorName"
                placeholder="请输入作者"
                :size="formItemSize"
                type="text"
                clearable
                maxlength="50"
                show-word-limit
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="2" :offset="20">
            <!-- 每次点击此按钮检索，都检索的是第0页 -->
            <el-button
              size="small"
              type="primary"
              plain
              @click="advancedSearch"
              icon="el-icon-search"
              >检索</el-button
            >
          </el-col>
          <el-col :span="2">
            <el-button
              size="small"
              plain
              @click="resetAdvancedForm('advancedForm')"
              icon="el-icon-refresh"
              >重置</el-button
            >
          </el-col>
        </el-row>
      </el-form>
    </el-card>
  </div>
</template>

<script lang="ts">
import { Component, Prop, Vue, Watch } from "vue-property-decorator";
import { advancedSearchArticles, getAllTags } from "@/apis/apis";
@Component({
  name: "searchBar",
})
export default class searchBar extends Vue {
  // 组件宽度属性
  @Prop({ type: Number, default: 900 }) searchBarWidth!: Number;
  // 检索结果的排序属性
  @Prop({ type: String, default: "synthesis" }) currentSortType!: String;
  // 首页跳转传递的标签
  @Prop({ type: Object }) tempTag!: any;
  // 监听父组件传递的数据
  @Watch("currentSortType")
  onCurrentSortTypeChange(val: string, oldVal: string) {
    this.advancedForm.sortType = val;
    // 将当前页码重置为0
    this.resetCurrentPage();
    this.onSubmitAdvancedForm();
  }
  @Watch("tempTag")
  onTagChange(val: any, oldVal: any) {
    // console.log(val, oldVal);
    // 将标签添加到检索表单中，只传id
    this.advancedForm.tagId.push(this.tempTag.tagId);
    this.onSubmitAdvancedForm();
  }

  // @Watch("advancedForm", { immediate: true, deep: true })
  // onDateChange(val: any, oldVal: any) {
  //   console.log(val, oldVal);
  //   console.log(val.kind);
  //   // 在提交表单检索前需要将日期格式化转为时间开始和结束的数组["2020-01-01","2020-01-02"]
  //   // 将标签添加到检索表单中
  //   // this.advancedForm.tags.push(val);
  //   // console.log(this.advancedForm.tags);
  // }

  // 组件初始化时获取所有的标签
  mounted() {
    this.getAllTags();
  }
  // 高级检索的表单数据,以及检索结果的排序方式
  advancedForm: {
    keyword: string;
    tagId: number[];
    kind: number[];
    createTime: Date[];
    authorName: string;
    sortType: string;
    pageSize: number;
    pageNo: number;
  } = {
    keyword: "",
    tagId: [],
    kind: [],
    authorName: "",
    createTime: [],
    sortType: "synthesis",
    pageSize: 10,
    pageNo: 0,
  };
  // 表单项目的大小控制
  formItemSize: string = "medium";
  // 日期的快捷选择项
  pickerOptions: object = {
    shortcuts: [
      {
        text: "最近一周",
        onClick(picker: any) {
          const end = new Date();
          const start = new Date();
          start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
          picker.$emit("pick", [start, end]);
        },
      },
      {
        text: "最近一个月",
        onClick(picker: any) {
          const end = new Date();
          const start = new Date();
          start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
          picker.$emit("pick", [start, end]);
        },
      },
      {
        text: "最近三个月",
        onClick(picker: any) {
          const end = new Date();
          const start = new Date();
          start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
          picker.$emit("pick", [start, end]);
        },
      },
    ],
  };

  //  存放所有的tag标签,赋初值占位
  allTags: Array<{ tagName: string; tagId: number }> = [
    {
      tagId: 1,
      tagName: "test",
    },
  ];

  // 更新高级检索form的当前页数据
  updateCurrentPage() {
    this.advancedForm.pageNo += 1;
    // return this.advancedForm.currentPage;
  }

  // 重置当前页码,es的是从0开始的
  resetCurrentPage() {
    this.advancedForm.pageNo = 0;
  }
  // 开始高级检索，检索的是第0页
  advancedSearch() {
    this.resetCurrentPage();
    this.onSubmitAdvancedForm();
  }

  // 提交高级检索的表单
  onSubmitAdvancedForm() {
    const isEmpty = this.isAdvancedFormEmpty();
    // 输入内容为空给出提示信息
    if (isEmpty) {
      this.$message.warning("请输入检索内容");
      return;
    } else {
      // 数据加载传递给父组件
      this.$emit("loading", true);
      console.log(this.advancedForm);
      advancedSearchArticles(this.advancedForm)
        .then((res) => {          
          if (res.data.code === "200") {
            console.log(res.data.data.total);
            
            // 将数据传递给父组件，由父组件进行处理
            this.$emit("searchResult", res.data.data.records);
            // 取消加载
            this.$emit("loading", false);
          } else {
            this.$message.error("数据查询失败请重试！");
          }
        })
        .catch((error) => {
          this.$message.error("检索失败请重试！");
          console.log(error);
        });
    }
  }

  /**
   * 重置高级检索的表单
   * @param formName 重置表单的名称
   */
  resetAdvancedForm(formName: string) {
    (this.$refs[formName] as any).resetFields();
  }
  /**
   * 判断表单是否为空，表单全部为空不能进行检索，即判断是否和初始化的表单数据相同
   */
  isAdvancedFormEmpty(): boolean {
    // 解构数据
    const isTitleAndContentEmpty = this.advancedForm.keyword === "";
    const isTagsEmpty = this.advancedForm.tagId.length === 0;
    const isArticleTypeEmpty = this.advancedForm.kind.length === 0;
    const isDateEmpty = this.advancedForm.createTime.length === 0;
    const isAuthorEmpty = this.advancedForm.authorName === "";
    // 使用&&只要有一项不为空&&返回的就是false
    return (
      isTitleAndContentEmpty &&
      isTagsEmpty &&
      isArticleTypeEmpty &&
      isDateEmpty &&
      isAuthorEmpty
    );
  }
  getAllTags() {
    getAllTags()
      .then((res) => {
        let resTags = res.data.data;
        resTags.sort((a: any, b: any) => a.tagId - b.tagId);
        // 将tags清空,清空之前的占位
        this.allTags = [];
        resTags.forEach((item: any) => {
          this.allTags.push({ tagId: item.tagId, tagName: item.tagName });
        });
        // 如果首页跳转传入的数据不为空，同时请求回的所有标签中存在对应的标签id和name,就加入到tags中
        if (Object.keys(this.tempTag).length > 0) {
          let isExist = this.allTags.some((item: any) => {
            return item.tagName === this.tempTag.tagName;
          });
          if (isExist) {
            this.allTags.push({
              tagId: this.tempTag.tagId,
              tagName: this.tempTag.tagName,
            });
          }
        }
      })
      .catch((err: any) => {
        console.log("this is error from searchBar getAllTags");
        console.log(err);
      });
  }
}
</script>

<style lang="scss" scoped>
@import "@/assets/styles/themes.scss";
.searchBar-container {
  // border: 1px solid red;
  .searchBar-card {
    @include useTheme {
      background-color: getVar("divColor");
      color: getVar("textColor");
    }
    &::v-deep(.el-card__body) {
      padding: 10px 20px;
    }
    .el-form-item {
      margin-bottom: 12px;
    }
  }
}
</style>